package com.lp.biz.operations.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.lp.biz.member.mapper.MemberMapper;
import com.lp.biz.member.model.entity.Member;
import com.lp.biz.message.service.BizMessageSystemService;
import com.lp.biz.operations.mapper.BizReadTaskMapper;
import com.lp.biz.operations.mapper.BizReadTaskMemberRelMapper;
import com.lp.biz.operations.mapper.BizReadTaskModeratorMapper;
import com.lp.biz.operations.model.entity.BizReadTask;
import com.lp.biz.operations.model.entity.BizReadTaskMemberRel;
import com.lp.biz.operations.model.entity.BizReadTaskModerator;
import com.lp.biz.operations.model.vo.TaskCreate;
import com.lp.biz.operations.model.vo.TaskList;
import com.lp.biz.operations.service.TaskService;
import com.lp.biz.operations.mapper.BizReadTaskApplyMapper;
import com.lp.biz.operations.model.entity.BizReadTaskApply;
import com.lp.biz.train.model.vo.ClassModerator;
import com.lp.common.entity.PageParams;
import com.lp.common.exception.BaseException;
import com.lp.common.exception.ErrorCodeEnum;
import com.lp.common.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.lp.common.constant.CommonConstant.NEGATE;
import static com.lp.common.constant.CommonConstant.SURE;
import static com.lp.common.constant.TrainConstant.*;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-08-06 20:59:48
 */
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private BizReadTaskMapper taskMapper;

    @Autowired
    private BizReadTaskApplyMapper taskApplyMapper;

    @Autowired
    private BizReadTaskModeratorMapper moderatorMapper;

    @Autowired
    private BizMessageSystemService messageSystemService;

    @Autowired
    private BizReadTaskMemberRelMapper taskMemberRelMapper;

    @Override
    public CommonResult getTaskApplyList(PageParams query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(taskApplyMapper.getTaskApplyList());
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateTaskApplyStatus(Integer applyId) {
        BizReadTaskApply apply = taskApplyMapper.selectById(applyId);
        if (apply == null) {
            throw new BaseException("申请信息错误");
        }
        taskApplyMapper.update(null, new UpdateWrapper<BizReadTaskApply>().lambda()
                .eq(BizReadTaskApply::getId, applyId)
                .set(BizReadTaskApply::getStatus, apply.getStatus().equals(SURE) ? NEGATE: SURE)
                .set(BizReadTaskApply::getSendAt, apply.getStatus().equals(SURE) ? null: LocalDateTime.now()));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateTaskApplyState(Integer applyId, Integer status) {
        BizReadTaskApply apply = taskApplyMapper.selectById(applyId);
        if (apply == null) {
            throw new BaseException("申请信息错误");
        }
        taskApplyMapper.update(null, new UpdateWrapper<BizReadTaskApply>().lambda()
                .eq(BizReadTaskApply::getId, applyId)
                .set(BizReadTaskApply::getState, status));
        messageSystemService.applyActivity(apply.getMemberId());
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addTask(TaskCreate taskCreate) {
        Long l = memberMapper.selectCount(new QueryWrapper<Member>().lambda().in(Member::getId, taskCreate.getMemberIds()));
        if (taskCreate.getMemberIds().size() != l) {
            throw new BaseException("人员输入错误");
        }
        BizReadTask task = new BizReadTask();
        task.setTheme(taskCreate.getTheme());
        task.setLocal(taskCreate.getLocal());
        task.setContent(taskCreate.getContent());
        task.setStartAt(taskCreate.getStartAt());
        task.setEndAt(taskCreate.getEndAt());
        task.setCreateAt(LocalDateTime.now());
        taskMapper.insert(task);
        List<BizReadTaskMemberRel> relList = new ArrayList<>();
        for (Integer memberId : taskCreate.getMemberIds()) {
            BizReadTaskMemberRel rel = new BizReadTaskMemberRel();
            rel.setTaskId(task.getId());
            rel.setMemberId(memberId);
            relList.add(rel);
        }
        taskMemberRelMapper.insertBatch(relList);
    }

    @Override
    public CommonResult getTasks(PageParams query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<TaskList> tasks = taskMapper.getTasks();
        LocalDateTime now = LocalDateTime.now();
        for (TaskList task : tasks) {
            if (now.isBefore(task.getStartAt())) {
                task.setStatus(CLASS_NOT_START);
            } else if (now.isAfter(task.getEndAt())) {
                task.setStatus(CLASS_ENDED);
            } else {
                task.setStatus(CLASS_STARTED);
            }
        }
        return CommonResult.restPage(tasks);
    }

    @Override
    public CommonResult getTaskDetail(Integer taskId) {
        return null;
    }

    @Override
    public CommonResult getMembers(Integer taskId, PageParams query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(taskMapper.getMembers(taskId));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateModerator(Integer taskId, ClassModerator moderator) {
        BizReadTask task = taskMapper.selectById(taskId);
        if (task == null) {
            throw new BaseException("活动不存在");
        }
        Long l = taskMemberRelMapper.selectCount(new QueryWrapper<BizReadTaskMemberRel>().lambda()
                .eq(BizReadTaskMemberRel::getTaskId, taskId)
                .eq(BizReadTaskMemberRel::getMemberId, moderator.getMemberId()));
        if (l == null || l == 0) {
            throw new BaseException("用户不存在");
        }
        BizReadTaskModerator one = moderatorMapper.selectOne(new QueryWrapper<BizReadTaskModerator>().lambda()
                .eq(BizReadTaskModerator::getTaskId, taskId));
        if (one == null) {
            BizReadTaskModerator bizReadTaskModerator = new BizReadTaskModerator();
            bizReadTaskModerator.setTaskId(taskId);
            bizReadTaskModerator.setMemberId(moderator.getMemberId());
            moderatorMapper.insert(bizReadTaskModerator);
        } else if (!one.getMemberId().equals(moderator.getMemberId())){
            throw new BaseException("已有主持人");
        } else {
            moderatorMapper.delete(new QueryWrapper<BizReadTaskModerator>().lambda()
                    .eq(BizReadTaskModerator::getTaskId, taskId)
                    .eq(BizReadTaskModerator::getMemberId, moderator.getMemberId()));
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateJoin(Integer memberId, Integer taskId) {
        BizReadTaskMemberRel rel = taskMemberRelMapper.selectOne(new QueryWrapper<BizReadTaskMemberRel>().lambda()
                .eq(BizReadTaskMemberRel::getTaskId, taskId)
                .eq(BizReadTaskMemberRel::getMemberId, memberId));
        if (rel == null) {
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
        taskMemberRelMapper.update(null, new UpdateWrapper<BizReadTaskMemberRel>().lambda()
                .eq(BizReadTaskMemberRel::getTaskId, taskId)
                .eq(BizReadTaskMemberRel::getMemberId, memberId)
                .set(BizReadTaskMemberRel::getIsJoin, rel.getIsJoin().equals(SURE) ?NEGATE: SURE));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateReview(Integer memberId, Integer taskId) {
        BizReadTaskMemberRel rel = taskMemberRelMapper.selectOne(new QueryWrapper<BizReadTaskMemberRel>().lambda()
                .eq(BizReadTaskMemberRel::getTaskId, taskId)
                .eq(BizReadTaskMemberRel::getMemberId, memberId));
        if (rel == null) {
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
        taskMemberRelMapper.update(null, new UpdateWrapper<BizReadTaskMemberRel>().lambda()
                .eq(BizReadTaskMemberRel::getTaskId, taskId)
                .eq(BizReadTaskMemberRel::getMemberId, memberId)
                .set(BizReadTaskMemberRel::getIsReview, rel.getIsReview().equals(SURE) ?NEGATE: SURE));
    }
}
